package cn.com.cetccst.mdmdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.system.Os;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zdk.mg.agent.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.com.cetccst.mdm.engine.IMDMEngine;
import cn.com.cetccst.mdm.MDMManager;
import cn.com.cetccst.mdm.engine.NotSupportException;
import cn.com.cetccst.mdmdemo.doubleApn.DoubleApnManager;
import cn.com.cetccst.mdmdemo.utils.FileInfoUtils;
import cn.com.cetccst.mdmdemo.utils.InputDialog;
import cn.com.cetccst.mdmdemo.utils.ThreadSafeToast;
import cn.com.cetccst.mdmdemo.utils.ToolbarActivity;

public class FunctionsActivity extends ToolbarActivity implements View.OnClickListener {
    private static final int kDisableApps = 2000;
    private static final int kInstallApps = 2001;
    private static final int kUninstallApps = 2002;
    private static final int kInstallSourceApps = 2003;
    private static final int kKeepAliveApps = 2004;
    private static final int kSuperApps = 2005;
    private static final int kNetworkApps = 2006;
    private static final int kEnableApps = 2007;
    private static final int kAccessibility = 2008;
    private static final int kUninstallblockApps = 2009;
    private static final int kUnknownSourceApps = 2010;
    private static final int kInstallblockApps = 2011;
    private IMDMEngine engine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_functions);
        initToolbar("功能测试");
        engine = MDMManager.getInstance().getMdmEngine();
        for (Integer key : functions.keySet()) {
            findViewById(key).setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        try {
            int id = v.getId();
            if (functions.containsKey(id)) {
                functions.get(id).onClick(v);
            } else {
                ThreadSafeToast.show("未实现功能");
            }
        } catch (NotSupportException e) {
            ThreadSafeToast.show("不支持：" + e.getMessage());
        } catch (Exception e) {
            ThreadSafeToast.show(e.getMessage());
            e.printStackTrace();
        }
    }

    public void handleDisallowRunningApps(View view) {
        List<String> blackListApps = engine.getDisallowRunningApps();
        AppListActivity.show(this, AppListActivity.kTypeApp, blackListApps, kDisableApps);
    }

    public void handleAllowRunningApps(View view) {
        List<String> blackListApps = engine.getDisallowRunningApps();
        AppListActivity.show(this, AppListActivity.kTypeApp, blackListApps, kDisableApps);
    }

    public void GetPermittedAccessibility(View view) {
        List<String> blackListApps = engine.getDisallowRunningApps();
        AppListActivity.show(this, AppListActivity.kTypeApp, null, kAccessibility);
    }


    public void handleEnableApps(View view) {
        List<String> blackListApps = engine.getDisallowRunningApps();
        AppListActivity.show(this, AppListActivity.kTypeApp, blackListApps, kEnableApps);
    }

    public void handleInstallblockApp(View view) {
        List<String> blackListApps = engine.getInstallblockApps();
        AppListActivity.show(this, AppListActivity.kTypeInstallBlocked, blackListApps, kInstallblockApps);
    }

    public void handleClearInstallblockApp(View view) {
        engine.setInstallblockApps(null);
    }

    public void handleUninstallblockApp(View view) {
        List<String> blackListApps = engine.getUninstallblockApps();
        AppListActivity.show(this, AppListActivity.kTypeUninstallBlocked, blackListApps, kUninstallblockApps);
    }

    public void handleClearMassStorage(View view) {
        engine.formatSDCard();
    }

    public void handleSilentInstallApp(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, kInstallApps);
    }

    public void handleSilentUninstallApp(View view) {
        AppListActivity.show(this, AppListActivity.kTypeSilentUninstall, null, kUninstallApps);
    }

    public void handleAppsCanInstallOtherApp(View view) {
        List<String> apps = engine.getInstallSourceApps();
        AppListActivity.show(this, AppListActivity.kTypeCanInstallApk, apps, kInstallSourceApps);
    }

    public void handleKeepAppAlive(View view) {
        List<String> apps = engine.getKeepLiveApps();
        AppListActivity.show(this, AppListActivity.kTypeKeepAlive, apps, kKeepAliveApps);
    }

    public void handleKeepNetworkAtSleepApps(View view) {
        List<String> apps = engine.getSuperApps();
        AppListActivity.show(this, AppListActivity.kTypeSuperApp, apps, kSuperApps);
    }

    public void handleNetworkAppWhiteList(View view) {
        List<String> apps = engine.getNetworkWhiteListApps();
        AppListActivity.show(this, AppListActivity.kTypeNet, apps, kNetworkApps);
    }

    public void handleNetworkAppBlockList(View view) {
        List<String> apps = engine.getNetworkWhiteListApps();
        AppListActivity.show(this, AppListActivity.kTypeNet, apps, kNetworkApps);
    }

    public void handleNetworkAddressWhiteList(View view) {
        String[] defaultValue = engine.getNetworkWhiteListAddress().toArray(new String[0]);
        InputDialog.getUserInput(this, "网络地址白名单", new String[]{"地址1", "地址2", "地址3", "地址4"}, defaultValue, values -> {
            try {
                engine.setNetworkWhiteListAddress(getDialogInput(values));
            } catch (Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

    public void handleNetworkAddressBlockList(View view) {
        List<String> apps = engine.getNetworkBlackListAddress();
        String[] defaultValue = engine.getNetworkBlackListAddress().toArray(new String[0]);
        InputDialog.getUserInput(this, "网络地址黑名单", new String[]{"地址1", "地址2", "地址3", "地址4"}, defaultValue, values -> {
            try {
                engine.setNetworkBlackListAddress(getDialogInput(values));
            } catch (Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

    public void handleFactoryReset(View view) {
        engine.factoryReset();
    }

    public void handleGetSN(View view) {
        ThreadSafeToast.show("SN:[" + engine.getSN() + "]");
    }

    public void handleSetDevicePassword(View view) {
        EditText editText = new EditText(this);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setView(editText)
                .setTitle("设定密码")
                .setMessage("请输入新密码")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setPositiveButton("设定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        engine.setDevicePassword(editText.getText().toString());
                        dialogInterface.dismiss();
                    }
                })
                .create();
        alertDialog.show();
    }


    public void handlePowerOnAt(View view) {
        engine.powerOnAt(0);
    }

    public void handleShutdown(View view) {
        engine.shutdown();
    }

    public void handleReboot(View view) {
        engine.reboot();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            try {
                if (requestCode == kDisableApps) {
                    List<String> blackListApps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setDisallowRunningApps(blackListApps, true);
                } else if (requestCode == kEnableApps) {
                    List<String> blackListApps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setDisallowRunningApps(blackListApps, false);
                } else if (requestCode == kUninstallblockApps) {
                    List<String> blackListApps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setUninstallblockApps(blackListApps);
                } else if (requestCode == kAccessibility) {
                    List<String> accessibilityListApps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setPermittedAccessibility(accessibilityListApps);
                } else if (requestCode == kInstallApps) {
                    String apkFile = FileInfoUtils.getPath(this, data.getData());
                    engine.installPackage(apkFile);
                } else if (requestCode == kUninstallApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    if (apps != null) {
                        for (String packageName : apps) {
                            engine.uninstallPackage(packageName);
                        }
                    }
                } else if (requestCode == kInstallSourceApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setInstallSourceApps(apps);
                } else if (requestCode == kKeepAliveApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setKeepLiveApps(apps);
                } else if (requestCode == kSuperApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setSuperApps(apps);
                } else if (requestCode == kNetworkApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setNetworkWhiteListApps(apps);
                } else if (requestCode == kUnknownSourceApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setUnknownSourceWhiteList(apps);
                } else if (requestCode == kInstallblockApps) {
                    List<String> apps = new Gson().fromJson(data.getStringExtra("apps"), AppListActivity.listType);
                    engine.setInstallblockApps(apps);
                }

            } catch (NotSupportException e) {
                ThreadSafeToast.show("不支持：" + e.getMessage());
            } catch (Exception e) {
                ThreadSafeToast.show(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public void handleAddApn(View view) {
        DoubleApnManager.handleAddApn();
    }

    public void handleDelApn(View view) {
        DoubleApnManager.handleDelApn();
    }

    public void handleQueryApn(View view) {
        DoubleApnManager.handleQueryApn();
    }

    public void handleActiveApn(View view) {
        DoubleApnManager.activeApn(Os.getuid());
    }

    public void handleSetDefaultApn(View view) {
        DoubleApnManager.handleSetDefaultApn(Os.getuid());
    }

    public void handleClearDefaultApn(View view) {
        DoubleApnManager.handleClearDefaultApn(Os.getuid());
    }

    public void handleQueryDefaultApn(View view) {
        DoubleApnManager.handleQueryDefaultApn(Os.getuid());
    }

    public void handleBluetoothWhiteList(View view) {
        String[] defaultValue = engine.getBluetoothWhiteList().toArray(new String[0]);
        InputDialog.getUserInput(this, "蓝牙Mac", new String[]{"数据1", "数据2", "数据3", "数据4"}, defaultValue, values -> {
            try {
                engine.setBluetoothWhiteList(getDialogInput(values));
            } catch (Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

    public void handleWIFIWhiteList(View view) {
        String[] defaultValue = engine.getWifiWhitList().toArray(new String[0]);
        InputDialog.getUserInput(this, "WifiSSID", new String[]{"数据1", "数据2", "数据3", "数据4"}, defaultValue, values -> {
            try {
                engine.setWifiWhiteList(getDialogInput(values));
            } catch (Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

    public void handleUnknownSourceWhiteList(View view) {
        List<String> apps = engine.getUnknownSourceWhiteList();
        AppListActivity.show(this, AppListActivity.kTypeUnknownSource, apps, kUnknownSourceApps);
    }

    private ArrayList<String> getDialogInput(String[] values) {
        ArrayList<String> data = new ArrayList<>();
        for (String value : values) {
            if (value != null && value.trim().length() > 0) {
                data.add(value);
            }
        }
        return data;
    }

    private static class FunctionWrapper {
        public int resId;
        public View.OnClickListener onClickListener;

        public FunctionWrapper(int resId, View.OnClickListener onClickListener) {
            this.resId = resId;
            this.onClickListener = onClickListener;
        }
    }


    private final Map<Integer, View.OnClickListener> functions = Map.ofEntries(
            Map.entry(R.id.btWL, this::handleBluetoothWhiteList),
            Map.entry(R.id.wifiWL, this::handleWIFIWhiteList),
            Map.entry(R.id.unknownSourceWL, this::handleUnknownSourceWhiteList),
            Map.entry(R.id.factoryReset, this::handleFactoryReset),
            Map.entry(R.id.getSN, this::handleGetSN),
            Map.entry(R.id.resetPassword, this::handleSetDevicePassword),
            Map.entry(R.id.powerOnAt, this::handlePowerOnAt),
            Map.entry(R.id.shutdown, this::handleShutdown),
            Map.entry(R.id.reboot, this::handleReboot),
            Map.entry(R.id.install, this::handleSilentInstallApp),
            Map.entry(R.id.uninstall, this::handleSilentUninstallApp),
            Map.entry(R.id.keepAlive, this::handleKeepAppAlive),
            Map.entry(R.id.sleepNetwork, this::handleKeepNetworkAtSleepApps),
            Map.entry(R.id.disallowInstall, this::handleInstallblockApp),
            Map.entry(R.id.disallowUninstall, this::handleUninstallblockApp),
            Map.entry(R.id.disallowRunning, this::handleDisallowRunningApps),
            Map.entry(R.id.allowRunning, this::handleAllowRunningApps),
            Map.entry(R.id.networkAppWL, this::handleNetworkAppWhiteList),
            Map.entry(R.id.networkAppBL, this::handleNetworkAppBlockList),
            Map.entry(R.id.networkAddrWL, this::handleNetworkAddressWhiteList),
            Map.entry(R.id.networkAddrBL, this::handleNetworkAddressBlockList),
            Map.entry(R.id.clearMassStorage, this::handleClearMassStorage),
            Map.entry(R.id.addAPN, this::handleAddApn),
            Map.entry(R.id.delAPN, this::handleDelApn),
            Map.entry(R.id.getAPN, this::handleQueryApn),
            Map.entry(R.id.activeAPN, this::handleActiveApn),
            Map.entry(R.id.setDefaultAPN, this::handleSetDefaultApn),
            Map.entry(R.id.clearDefaultAPN, this::handleClearDefaultApn),
            Map.entry(R.id.getDefaultAPN, this::handleQueryDefaultApn)
    );
}